package com.freek.ScreenDrop;

import java.awt.event.KeyEvent;
import java.util.prefs.Preferences;

import javax.swing.KeyStroke;

public class KeyCombo
{
	
	private static final String KEY_SUFFIX = "_KEYCODE";
	private static final String MODIFIERS_SUFFIX = "_MODIFIERS";
	private int keyCode;
	private int modifiers;
	
	public KeyCombo(int keyCode, int modifiers)
	{
		this.keyCode = keyCode;
		this.modifiers = modifiers;
		
	}
	
	public String getTextRepresentation()
	{
		int tempModifiers = modifiers;

		if(keyCode==KeyEvent.VK_SHIFT)
			tempModifiers &= ~KeyEvent.SHIFT_MASK;
		if(keyCode==KeyEvent.VK_CONTROL)
			tempModifiers &= ~KeyEvent.CTRL_MASK;
		if(keyCode==KeyEvent.VK_ALT)
			tempModifiers &= ~KeyEvent.ALT_MASK;
		if(keyCode==KeyEvent.VK_META)
			tempModifiers &= ~KeyEvent.META_MASK;
		return KeyEvent.getModifiersExText(tempModifiers) + 
				((tempModifiers!=0)?"+":"") + KeyEvent.getKeyText(keyCode);
	}
	
	public void put(Preferences prefs, String key)
	{
		prefs.putInt(key+KEY_SUFFIX, keyCode);
		prefs.putInt(key+MODIFIERS_SUFFIX, modifiers);
	}
	
	public static KeyCombo get(Preferences prefs, String key, KeyCombo defaultCombo)
	{
		int keyCombo = prefs.getInt(key+KEY_SUFFIX, defaultCombo.keyCode);
		int modifiers = prefs.getInt(key+MODIFIERS_SUFFIX, defaultCombo.modifiers);
		return new KeyCombo(keyCombo, modifiers);
	}
	
	/**
	 * Checks if this KeyCombo is contained or equal to the other KeyCombo
	 * @param other 
	 * @return
	 */
	public boolean matches(KeyCombo other)
	{
		return (this.keyCode==other.keyCode) && ((this.modifiers & other.modifiers) == this.modifiers);
	}
}
